package net1;

import java.io.File;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;

public class UdpEchoServer {
    private static final int port = 8888;
    private static final String base_path = "";

    public static void main(String[] args) throws IOException {
        DatagramSocket socket = new DatagramSocket(port);
        while (true) {
            byte[] requestData = new byte[1024];
            DatagramPacket requestPacket = new DatagramPacket(requestData, requestData.length);
            System.out.println("--------------------------------------");
            System.out.println("等待接收udp数据报");
            socket.receive(requestPacket);
            System.out.println("客户端ip: " + requestPacket.getAddress().getHostAddress());
            System.out.println("客户端port :" + requestPacket.getPort());

            for (int i = 0; i < requestData.length; i++) {
                byte b = requestData[i];
                if (b == '\3') {
                    String request = new String(requestData, 0, i);
                    System.out.println("客户端请求的文件列表路径为：" + base_path + request);
                    File dir = new File(base_path + request);
                    File[] files = dir.listFiles();
                    StringBuilder response = new StringBuilder();
                    if (files != null) {
                        for (File f : files) {
                            response.append(f.getName() + "\n");
                        }
                    }
                    response.append("\3");
                    byte[] responseData = response.toString().getBytes(StandardCharsets.UTF_8);
                    DatagramPacket responsePacket = new DatagramPacket(responseData, responseData.length, requestPacket.getSocketAddress());
                    socket.send(responsePacket);
                    break;
                }
            }
        }
    }
}
